package org.framework.lazy.cloud.network.heartbeat.protocol.route;

import org.wu.framework.core.NormalUsedString;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 路由上下文
 */
public class RouteContext {


    // key 验证ip、端口、类型
    private static final ConcurrentHashMap<String, ProxyRoute> m = new ConcurrentHashMap<>();


    /**
     * 设置路由
     *
     * @param route 路由
     */
    public static void setRoute(ProxyRoute route) {
        RouteType routeType = route.getRouteType();
        String virtualIp = route.getVirtualIp();
        String virtualPort = route.getVirtualPort();
        String key = virtualIp + ":" + virtualPort + "_" + routeType;
        if (m.containsKey(key)) {
            m.put(key, route);
            return;
        }
        // TODO 验证ip、端口、类型
        m.put(key, route);
    }

    /**
     * 获取路由
     *
     * @param virtualIp   原始ip
     * @param virtualPort 原始端口
     */
    public static ProxyRoute getRoute(String virtualIp, String virtualPort) {
        ProxyRoute p = m.values()
                .stream()
                .filter(route -> route.getVirtualIp().equals(virtualIp)
                        &&
                        (route.getVirtualPort().equals(virtualPort) || route.getVirtualPort().equals(NormalUsedString.ASTERISK)))
                .findFirst()
                .orElse(null);
        return p;
    }

    /**
     * 删除路由
     *
     * @param virtualIp   原始ip
     * @param virtualPort 原始端口
     */
    public static void removeRoute(String virtualIp, String virtualPort, RouteType routeType) {
        String key = virtualIp + ":" + virtualPort + "_" + routeType;
        m.remove(key);

    }
}
